<template>
    <has-left-nav-layout>
        <template v-slot:leftNav>
            <left-menu :lists="menus" v-model="curMenu" @change="getData"/>
        </template>
        <main-wrap 
            :loading="true" 
            ref="mianEle" 
            :load="onLoad" 
            :end="page.finished" 
            :noFixed="true" bodyBg="none"
            :showOverTxt="page.lists.length>0" 
            :pageIndex="page.pageIndex">
            <template v-slot:header>
                <div class="adheader">
                    <div class="hcon">
                        <div class="shopLetfTop">
                            <b>{{total}}</b> {{titleText}}
                        </div>
                        <div class="topSearch">
                            <div class="tswd">
                                <my-search v-model="keyword" :placeholder="search" @onSearch="resetScroll"/>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
            <div class="goodsMainCon">
                <!-- <div class="ctgbox">
                    <two-tab/>
                </div> -->
                <div class="goodsTabSearchBox">
                    <sort :lists="sortData" @change="getSortData"/>
                </div>
                <goods-list :lists="page.lists" :type="2" :listType="2" @onClick="openDetail"/>
                <emptyGame v-if="page.finished && page.lists.length<1" title="" />
            </div>
        </main-wrap>
        <my-dailog v-model:show="showFlag" :showtopclose="true" :styleType="5">
            <detail :detail='details' :id="details.adPlaceId" :type='2'/>
        </my-dailog>
    </has-left-nav-layout>
</template>

<script>
import { reactive,toRefs,getCurrentInstance,onMounted,computed,onBeforeUnmount} from 'vue'
import {useRoute,useRouter} from 'vue-router'
import { useStore } from 'vuex'
import hasLeftNavLayout from '@/components/hasLeftNavLayout.vue'
import leftMenu from '@/components/leftMenu.vue'
import mainWrap from '@/components/mainWrap.vue'
import mySearch from '@/components/mySearch.vue'
import Image from '@/components/image.vue';
import goodsList from '@/components/goodsList.vue';
import sort from '@/components/sort.vue';
//import twoTab from '@/components/twoTab.vue'
import detail from '../components/adDetail/detail.vue'
import myDailog from '@/components/myDailog.vue'
import emptyGame from '@/components/emptyGame.vue'
import {toast,myOverlay} from '@/utils/common.js'
import { useI18n } from 'vue-i18n'

export default {
    components:{
       hasLeftNavLayout,
       leftMenu,
       mainWrap,
       mySearch,
       Image,
       goodsList,
       sort,
       //twoTab,
       detail,
       myDailog,
       emptyGame
    },
    props:{

    },
    setup(props,context){
        const router = useRouter()
        const route = useRoute()
        const store = useStore()
        const {proxy} = getCurrentInstance()
        const {t} = useI18n()
        const state = reactive({
            userInfo:computed(()=>store.state.base.userInfo),
            keyword:'',
            page:{
                lists:[],
                pageIndex:1,
                pageSize:20,
                finished: false
            },
            sortParams:{
                orderField: 'total_pv',
                orderType: "desc",
            },
            menus:[
                // {name:'My',num:'',id:'adspace_tab_1'},
                // {name:'Whole',num:'',id:'adspace_tab_2'},
               // {name:'Set',path:'/ad/set'}
            ],
            curMenu:'adspace_tab_2',
            sortData:[
                {id:1,name:t('prop.tab3'),noShow:true},
                {id:2,name:t('prop.tab4'),noShow:true},
                 {id:'total_uv',name:t('prop.tab5')}
                // {id:4,name:'Advertising'}
            ],
            showFlag:false,
            total:0,
            details:'',
            arLandmarkId:'',
            st1:'',
            st2:'',
            userType:'',
            titleText:t('public.total'),
            search:t('public.search')
        })
        onMounted(()=>{
            myOverlay.open()
            state.arLandmarkId = route.query.cityid
            state.userType = route.query.userType
            
            // 获取城市下的数据时，重新设置菜单
            if(state.arLandmarkId){
                state.curMenu = ''
                state.menus=[
                    {name:t('prop.tab8'),key:'adNum', num:0,path:`/ad/space?cityid=${state.arLandmarkId}&userType=${state.userType}`},
                    {name:t('prop.tab9'),key:'propNum',num:0,path:`/prop?cityid=${state.arLandmarkId}`},
                    {name:t('prop.tab10'),key:'shopNum',num:0,path:`/shop/list?cityid=${state.arLandmarkId}`},
                    {name:t('prop.tab11'),key:'gameNum',num:0,path:`/game?cityid=${state.arLandmarkId}`},
                    {name:t('prop.tab12'),key:'VenuesNum',num:0,path:`/venues?cityid=${state.arLandmarkId}`}
                ]
                getCityTotal()  // 获取数量
            }
            if(route.query.id){
                // 直接打开对应id的详情弹窗
                state.details = {}
                state.details.adPlaceId = route.query.id
                state.showFlag = true
            }
            state.st1 = setTimeout(()=>{onLoad()},2000)
            
        })

        onBeforeUnmount(()=>{  // 销毁组件
            myClearTimeOut()
        })

        const myClearTimeOut = ()=>{
            clearTimeout(state.st1)
            clearTimeout(state.st2)
        }

        // 获取城市下的广告位、道具、店铺等数量
        const getCityTotal = ()=>{
            store.dispatch('base/get_arLandmarkek_detail',{
                arLandmarkId:state.arLandmarkId,
                walletAddress: state.userInfo.walletAddress
            }).then(res =>{
               
                if(res.success){
                     state.menus.map((item)=>{
                         if(res.data[item.key]){
                              item.num=res.data[item.key]||'0'
                         }else{
                             item.num='0'
                         }
                         return item
                     })
                }
            })
        }

        
        const onLoad = ()=> {
            // 此函数必须返回一个Promise对象
            let params = {}
            // if(state.curMenu=='adspace_tab_1'){
            //     params={walletAddress: state.userInfo.walletAddress}
            // }
             params={walletAddress:state.userType?state.userInfo.walletAddress:''}
            return new Promise((resolve, reject) => {
                state.st2 = setTimeout(async () => {
                    const res = await store.dispatch('ad/get_adspace_list', {
                        page: state.page.pageIndex,
                        limit: state.page.pageSize,
                        ...state.sortParams,
                        placeStatus:state.sortParams.orderField==2?2:'',
                        adPlaceTitle:state.keyword,
                        arLandmarkId:state.arLandmarkId,
                        ...params
                    });
                    state.page.lists = [...state.page.lists, ...res.data];
                    state.page.pageIndex++;
                    state.total = res.total
                    // if(!state.menus[0].num && state.curMenu=='adspace_tab_1'){
                    //     state.menus[0].num = res.total
                    // }
                    // if(!state.menus[1].num && state.curMenu=='adspace_tab_2'){
                    //     state.menus[1].num = res.total
                    // }
                    if (state.page.lists.length >= res.total) {
                        state.page.finished = true;
                    }
                    myOverlay.close()
                    resolve(true);
                }, 500);
            });
        }
        const resetScroll = async()=>{
            myOverlay.open()
            proxy.$refs.mianEle.stopScroll()
            state.page.lists=[]
            state.page.pageIndex=1
            state.page.finished=false
            await onLoad()
            proxy.$refs.mianEle.initScroll()
        }
        const getSortData = sortParams =>{
            state.sortParams = sortParams
            resetScroll()
        }

        const getData = id=>{
            state.curMenu = id
            resetScroll()
        }
        const openDetail = item=>{
            state.details = item
            state.showFlag = true
        }

        return{
            ...toRefs(state),
            onLoad,
            getData,
            openDetail,
            resetScroll,
            getSortData
        }
    }
}
</script>

<style lang="scss" scoped>
    .adheader{
         padding: 15px 30px 15px 0;
        .hcon{
            display: flex;
            height: 80px;
            line-height: 80px;
            align-items: center;
            font-family: Inter-Medium, Inter;
            .shopLetfTop{
                padding: 0;
                font-weight: 500;
                font-size: 28px;
                font-family: Inter-Medium, Inter;
                b{
                    color: #82FEF4;
                }
            }
            .topSearch{
                flex: 1;
                // display: flex;
                // justify-content: end;
                .tswd{
                    float:right;
                    width: 550px;
                }
            }
        }
    }
    .goodsMainCon{
        padding: 10px 0 0 0;
    }
    .goodsTabSearchBox{
        display: inline-block;
        height: 55px;
        background: url(/images/gloabAdSplace/tsc.png) left top no-repeat;
        background-size: 100% 100%;
        padding: 0 30px;
    }
    .ctgbox{
        width: 100%;
        padding: 0 0 20px 0;
    }
    .ads-detail-box{
        width: 100%;
        height: 100%;
        padding: 30px 30px 30px 105px;
        .ads-main-bg{
            position: relative;
            z-index: 100;
            height: 100%;
            width: 100%;
            padding: 30px;
            background: url(/images/bigdg2.png) left top no-repeat;
            background-size: 100% 100%;
            overflow: hidden;
            .ads-close{
                position: absolute;
                z-index: 100;
                right: 35px;
                top: 35px;
                font-size: 40px;
                color: #67F8FF;
            }
        }
    }
</style>